/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName ApplicationStyleUpdater.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model.application
{
	
	import com.gesturesoft.imultimax.AppConst;
	import com.gesturesoft.imultimax.model.DataBaseManager;
	import com.gesturesoft.imultimax.model.application.interfaces.IApplicationUpdater;
	import com.gesturesoft.imultimax.model.error.DataBaseError;
	import com.gesturesoft.imultimax.model.interfaces.IDatabaseManager;
	import com.gesturesoft.imultimax.model.vo.AppVO;
	import com.gesturesoft.imultimax.model.vo.AssetVO;
	import com.gesturesoft.imultimax.model.vo.StyleMainVO;
	import com.gesturesoft.imultimax.model.vo.StyleVO;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.FaultEvent;
	
	/**
	 * Add asset details to database
	 */ 
	public class ApplicationStyleUpdater implements IApplicationUpdater
	{
		
		private static const EDIT:String = 'edit';
		private static const ADD:String = 'add';
		
		private var _iDBManager:IDatabaseManager;
		
		private var _configDetails:ArrayCollection;
		private var _styles:ArrayCollection;
		private var _currentCompany:String;
		
		public function ApplicationStyleUpdater(configDetails:ArrayCollection, styles:ArrayCollection)
		{
			
			_iDBManager = new DataBaseManager();
			_iDBManager.setTransactionStartPoint();
			
			_configDetails = configDetails;
			_styles = styles;
			
		}
		
		public function update():void
		{
			
			insertConfig();
			insertStyleDetails();
			
			_iDBManager.commitTransaction();
			
		}
		
		/**
		 * Insert asset version and style version to a main table
		 * asset and style details to 2 separate tables
		 */ 
		private function insertStyleDetails():void
		{
			
			//_iDBManager.prepareTable("style_main");
			
			for each(var styleMainVO:StyleMainVO in _styles)
			{
				
				var query:String;
				var resultRecord:ArrayCollection;
				
				//Check for style main table entry
				query = "SELECT * FROM IM_STYLE_MAIN WHERE sm_company ='"+styleMainVO.company+"'";
				resultRecord = retrieveHandler(query);
				
				if(resultRecord.length == 0) //new record 
				{
					
					insertHandler(
						"INSERT INTO IM_STYLE_MAIN (sm_asset_version, sm_style_version, sm_company) " + 
						"VALUES('"+ 
						styleMainVO.assetVersion +"','" + 
						styleMainVO.styleVersion +"','" + 
						styleMainVO.company +"')");
					
					insertAssets( styleMainVO.assets, styleMainVO.company );
					insertStyles( styleMainVO.styles, styleMainVO.company );
					
				}
				else //Existing record :- Check whether updation needed for asset or style
				{
					
					//START:Updation for assets
					query = "SELECT sm_asset_version FROM IM_STYLE_MAIN WHERE sm_company ='"+styleMainVO.company+"'";
					
					var styleMainRow:ArrayCollection = retrieveHandler(query);
					
					if( styleMainRow[0].sm_asset_version != styleMainVO.assetVersion ) //Need updation
					{
						
						// Update style main table
						updateHandler("UPDATE IM_STYLE_MAIN SET sm_asset_version='"+styleMainVO.assetVersion+"' WHERE sm_company='"+styleMainVO.company+"'"); 
						query = "DELETE FROM IM_ASSETS WHERE as_company='"+styleMainVO.company+"'";
						executeHandler(query); //Delete existing assets details
						insertAssets( styleMainVO.assets, styleMainVO.company );
						
					}
					//END:Updation for assets
					
					//START:Updation for styles
					query = "SELECT sm_style_version FROM IM_STYLE_MAIN WHERE sm_company ='"+styleMainVO.company+"'";
					styleMainRow = retrieveHandler(query);
					
					if( styleMainRow[0].sm_style_version != styleMainVO.styleVersion ) //Need updation
					{
						
						// Update style main table
						updateHandler("UPDATE IM_STYLE_MAIN SET sm_style_version='"+styleMainVO.styleVersion+"' WHERE sm_company='"+styleMainVO.company+"'"); 
						query = "DELETE FROM styles WHERE company='"+styleMainVO.company+"'";
						executeHandler(query); //Delete existing assets details
						insertStyles( styleMainVO.styles, styleMainVO.company );
						
					}
					//END:Updation for styles
					
				}
				
			}
			
		}
		
		/**
		 * Inserting config details to table companies
		 */ 
		private function insertConfig():void
		{
			
			for each(var appVO:AppVO in _configDetails)
			{
				
				_iDBManager.prepareTable("companies"); //Create table if not exist
				
				if(appVO.mode == ADD) //Means the entry is new 
				{
					
					insertHandler(
						"INSERT INTO IM_COMPANIES (cmp_version, cmp_company, cmp_server, cmp_configFile, cmp_is_enable, cmp_startup, cmp_asset_version, cmp_style_version, cmp_currency ) " + 
						"VALUES('"+ 
						appVO.version +"','" + 
						appVO.name +"','" + 
						appVO.server +"','"+ 
						appVO.configFile +"','"+
						appVO.isEnable.toString() +"','"+
						appVO.startUp.toString() +"','"+
						appVO.assetVersion +"','"+
						appVO.styleVersion.toString() +"','" +
						appVO.currency.toString()+"')");
					
					
				}
				else //Update the existing entry
				{
					
					//"UPDATE ClientSettings SET "+fieldName + "='"+ fieldValue+"'";\
					
					if(appVO.startUp.toString() == "1")
					{
						
						//START:Update startup company
						updateHandler("UPDATE IM_COMPANIES SET cmp_startup='0'");
						updateHandler("UPDATE IM_COMPANIES SET cmp_startup='1' WHERE cmp_company='"+appVO.name+"'");
						//trace("UPDATE companies SET startup='1' WHERE appname='"+appVO.name+"'");
						//END:Update startup company
						
					}
					else
					{
						
						updateHandler(
							"UPDATE IM_COMPANIES SET cmp_version='"+appVO.version+"', cmp_company='"+appVO.name+"', cmp_server='"+appVO.server+"'," +
							" cmp_configFile='"+appVO.configFile+"', cmp_is_enable='"+appVO.isEnable.toString()+"', cmp_startup='"+appVO.startUp.toString()+"'," +
							" cmp_asset_version='"+appVO.assetVersion+"', cmp_style_version='"+appVO.styleVersion.toString()+"' WHERE cmp_company='"+appVO.name+"'");
						
					}
					
				}
				
			}
			
		}
		
		/**
		 * Insert asset details
		 */ 
		private function insertAssets( assets:ArrayCollection, company:String ):void
		{
			
			//_iDBManager.prepareTable("assets");
			
				
			for each(var assetVO:AssetVO in assets)
			{
				
				insertHandler(
					"INSERT INTO IM_ASSETS ( as_name, as_type, as_value, as_company, as_active_table_propery ) " + 
					"VALUES('"+ 
					assetVO.name +"','" + 
					assetVO.type +"','" + 
					assetVO.value +"','"+ 
					company +"','" +
					assetVO.activeTablePropery+"')");
				
			}
				
			
		}
		
		/**
		 * Insert style details
		 */
		private function insertStyles(styles:ArrayCollection, company:String):void
		{
			
			//_iDBManager.prepareTable("styles");
			
			for each(var styleVO:StyleVO in styles)
			{
				
				insertHandler(
					"INSERT INTO IM_STYLES ( st_class_name, st_property, st_value, st_company, st_active_table_propery, st_active_table_sub_propery ) " + 
					"VALUES('"+ 
					styleVO.className +"','" + 
					styleVO.property +"','" + 
					styleVO.value +"','"+ 
					company +"','" +
					styleVO.activeTablePropery+"','" +
					styleVO.activeTableSubPropery+"')");
				
			}
			
		}
		
		private function insertHandler(val:String):void
		{
			
			try
			{
				
				_iDBManager.insertValues(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("ApplicationStyleUpdator-insertHandler() : Database insertion error");
				throw error;
				
			}
			
		}
		
		private function updateHandler(val:String):void
		{
			
			try
			{
				
				_iDBManager.update(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("ApplicationStyleUpdator-updateHandler() : Database updation error");
				throw error;
				
			}
			
		}
		
		private function retrieveHandler(val:String):ArrayCollection
		{
			
			var result:ArrayCollection;
			
			try
			{
				
				result = _iDBManager.getData(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("ApplicationStyleUpdator-retrieveHandler() : Database Read error");
				throw error;
				
			}
			
			return result;
			
		}
		
		private function executeHandler(val:String):void
		{
			
			try
			{
				
				_iDBManager.execute(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("ApplicationStyleUpdator-executeHandler() : Database execution error");
				throw error;
				
			}
			
		}
		
	}
	
}